/**
 * 文件上传服务
 * 处理文件分片上传、合并和状态查询的API调用
 */

// 服务器API基础URL
const API_BASE_URL = 'http://localhost:3000/api';

/**
 * 上传单个文件分片
 * @param {Number} chunkIndex - 分片索引
 * @param {Object} file - 文件对象
 * @returns {Promise}
 */
export const uploadChunk = async (chunkIndex, file) => {
  // 如果文件已暂停，则中断上传
  if (file.paused) {
    throw new Error('Upload paused');
  }

  const chunk = file.chunks[chunkIndex];
  const formData = new FormData();
  
  // 添加分片数据和元信息到FormData
  formData.append('chunk', chunk.data);
  formData.append('fileId', file.fileId);
  formData.append('chunkIndex', chunkIndex);
  formData.append('totalChunks', file.chunks.length);
  formData.append('filename', file.name);

  try {
    // 使用fetch API发送请求，并传入AbortController的signal用于取消请求
    const response = await fetch(`${API_BASE_URL}/upload/chunk`, {
      method: 'POST',
      body: formData,
      signal: file.controller?.signal,
  
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || '上传分片失败');
    }

    // 标记该分片为已上传
    file.uploadedChunks[chunkIndex] = true;
    
    // 更新文件上传进度
    const uploadedCount = file.uploadedChunks.filter(Boolean).length;
    file.progress = Math.floor((uploadedCount / file.chunks.length) * 100);
    
    return await response.json();
  } catch (error) {
    // 如果不是因为取消操作导致的错误，则重新抛出
    if (error.name !== 'AbortError') {
      console.error(`分片 ${chunkIndex} 上传失败:`, error);
      throw error;
    }
    throw error;
  }
};

/**
 * 合并文件分片
 * @param {String} fileId - 文件唯一标识
 * @returns {Promise}
 */
export const mergeChunks = async (fileId) => {
  try {
    const response = await fetch(`${API_BASE_URL}/upload/merge`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ fileId })
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || '合并文件失败');
    }

    return await response.json();
  } catch (error) {
    console.error('合并文件失败:', error);
    throw error;
  }
};

/**
 * 获取文件上传状态
 * @param {String} fileId - 文件唯一标识
 * @returns {Promise}
 */
export const getUploadStatus = async (fileId) => {
  try {
    const response = await fetch(`${API_BASE_URL}/upload/status?fileId=${fileId}`);

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || '获取上传状态失败');
    }

    return await response.json();
  } catch (error) {
    console.error('获取上传状态失败:', error);
    throw error;
  }
};

/**
 * 取消文件上传
 * @param {String} fileId - 文件唯一标识
 * @returns {Promise}
 */
export const cancelUpload = async (fileId) => {
  try {
    const response = await fetch(`${API_BASE_URL}/upload/cancel`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ fileId })
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || '取消上传失败');
    }

    return await response.json();
  } catch (error) {
    console.error('取消上传失败:', error);
    throw error;
  }
};